package com.ctshk.rpc.order.tour.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.utils.Assist;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.order.tour.code.AdjustTypeCode;
import com.ctshk.rpc.order.tour.code.CollectionStatusCode;
import com.ctshk.rpc.order.tour.code.IsDeletedCode;
import com.ctshk.rpc.order.tour.code.PlusTypeCode;
import com.ctshk.rpc.order.tour.entity.SeriesOrderTouristFeeAdjust;
import com.ctshk.rpc.order.tour.entity.SeriesOrderTouristInfo;
import com.ctshk.rpc.order.tour.entity.SeriesOrderTouristVisa;
import com.ctshk.rpc.order.tour.mapper.SeriesOrderTouristFeeAdjustMapper;
import com.ctshk.rpc.order.tour.mapper.SeriesOrderTouristInfoMapper;
import com.ctshk.rpc.order.tour.mapper.SeriesOrderTouristVisaMapper;
import com.ctshk.rpc.order.tour.req.*;
import com.ctshk.rpc.order.tour.service.ISeriesOrderTouristFeeAdjustService;
import com.ctshk.rpc.order.tour.service.ISeriesOrderTouristInfoService;
import com.ctshk.rpc.order.tour.service.ISeriesOrderTouristVisaService;
import com.ctshk.rpc.tour.service.ISeriesTripScheduleService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 谭响
 * @since 2021-01-22
 */
@DubboService
public class SeriesOrderTouristFeeAdjustServiceImpl extends ServiceImpl<SeriesOrderTouristFeeAdjustMapper, SeriesOrderTouristFeeAdjust> implements ISeriesOrderTouristFeeAdjustService {

    @Autowired
    private SeriesOrderTouristVisaMapper seriesOrderTouristVisaMapper;

    @Autowired
    private ISeriesOrderTouristVisaService iSeriesOrderTouristVisaService;

    @Autowired
    private SeriesOrderTouristFeeAdjustMapper seriesOrderTouristFeeAdjustMapper;

    @DubboReference
    private ISeriesTripScheduleService iSeriesTripScheduleService;
    
    @Autowired
    ISeriesOrderTouristInfoService iSeriesOrderTouristInfoService;

    /**
     * 添加
     */
    @Override
    @Deprecated
    @Transactional(rollbackFor = Exception.class)
    public Result add(SeriesOrderTouristFeeAdjustAddReq req) {
        SeriesOrderTouristFeeAdjust seriesOrderTouristFeeAdjust = EntityUtil.copy(req, SeriesOrderTouristFeeAdjust.class);
        LocalDateTime now = LocalDateTime.now();
        seriesOrderTouristFeeAdjust.setGmtCreate(now);
        seriesOrderTouristFeeAdjust.setGmtModified(now);
        seriesOrderTouristFeeAdjust.setCreateId(req.getUserId());
        seriesOrderTouristFeeAdjust.setModifiedId(req.getUserId());
        seriesOrderTouristFeeAdjust.setIsDeleted(IsDeletedCode.NO.getCode());
        save(seriesOrderTouristFeeAdjust);
        return Result.success();
    }

    /**
     * 插入批量
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveBatch(List<SeriesOrderTouristFeeAdjustSaveBatchReq> listReq) {
        LocalDateTime now = LocalDateTime.now();
        List<SeriesOrderTouristFeeAdjust> feeAdjustList = new ArrayList<>();
        for (SeriesOrderTouristFeeAdjustSaveBatchReq saveBatchReq : listReq) {
            SeriesOrderTouristFeeAdjust feeAdjust = EntityUtil.copy(saveBatchReq, SeriesOrderTouristFeeAdjust.class);
            feeAdjust.setGmtCreate(now);
            feeAdjust.setGmtModified(now);
            feeAdjust.setCreateId(saveBatchReq.getUserId());
            feeAdjust.setModifiedId(saveBatchReq.getUserId());
            feeAdjust.setIsDeleted(IsDeletedCode.NO.getCode());

            feeAdjustList.add(feeAdjust);
        }

        return super.saveBatch(feeAdjustList);
    }

    /**
     * 添加批量
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addBatch(SeriesOrderTouristFeeAdjustAddBatchReq req) {
    	//调整总费用
    	BigDecimal allFeeAdjustAmount = calcAllFeeAdjustAmount(req.getItemList());
    	
        List<SeriesOrderTouristVisaSaveBatchReq> saveVisaList = new ArrayList<>();
        List<SeriesOrderTouristFeeAdjust> saveObjectList = new ArrayList<>();
        for (Long touristId : req.getTouristIdList()) {
            for (SeriesOrderTouristFeeAdjustAddBatchItemReq itemReq : req.getItemList()) {
                //检查是否保存调整费用
                if(Objects.equals(itemReq.getAdjustType(), AdjustTypeCode.INSURANCE.getCode())) {
                    //保险只能买一个，不能产生多个调整费用
                    QueryWrapper<SeriesOrderTouristFeeAdjust> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getOrderId, req.getOrderId());
                    queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getTouristId, touristId);
                    queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getAdjustType, AdjustTypeCode.INSURANCE.getCode());
                    queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getIsDeleted, IsDeletedCode.NO.getCode());
                    List<SeriesOrderTouristFeeAdjust> dbFeeAdjustList = seriesOrderTouristFeeAdjustMapper.selectList(queryWrapper);
                    if (dbFeeAdjustList.size() > 0) {
                        continue;
                    }
                } else {
                    QueryWrapper<SeriesOrderTouristFeeAdjust> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getOrderId, req.getOrderId());
                    queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getTouristId, touristId);
                    queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getRelationId, itemReq.getRelationId());
                    queryWrapper.lambda().eq(SeriesOrderTouristFeeAdjust::getIsDeleted, IsDeletedCode.NO.getCode());
                    List<SeriesOrderTouristFeeAdjust> dbFeeAdjustList = seriesOrderTouristFeeAdjustMapper.selectList(queryWrapper);
                    if (dbFeeAdjustList.size() > 0) {
                        continue;
                    }
                }

                //个性化业务处理
                if (Objects.equals(itemReq.getAdjustType(), AdjustTypeCode.INSURANCE.getCode())) {
                    //Ignore
                } else if (Objects.equals(itemReq.getAdjustType(), AdjustTypeCode.VISA.getCode())) {
                    //一个游客签证记录只能有一条，调整费用是多条
                    QueryWrapper<SeriesOrderTouristVisa> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(SeriesOrderTouristVisa::getOrderId, req.getOrderId());
                    queryWrapper.lambda().eq(SeriesOrderTouristVisa::getTouristId, touristId);
                    SeriesOrderTouristVisa dbVisa = seriesOrderTouristVisaMapper.selectOne(queryWrapper);
                    SeriesOrderTouristVisaSaveBatchReq visa = null;
                    //save or update
                    if(dbVisa == null) {
                        visa = new SeriesOrderTouristVisaSaveBatchReq();
                        visa.setOrderId(req.getOrderId());
                        visa.setTouristId(touristId);
                        visa.setVisaAmount(itemReq.getAmount());
                        visa.setCollectionStatus(CollectionStatusCode.NOT.getCode());
                    } else {
                        visa = EntityUtil.copy(dbVisa, SeriesOrderTouristVisaSaveBatchReq.class);
                        visa.setVisaAmount(visa.getVisaAmount().add(itemReq.getAmount()));
                    }
                    saveVisaList.add(visa);
                }

                SeriesOrderTouristFeeAdjust feeAdjust = EntityUtil.copy(itemReq, SeriesOrderTouristFeeAdjust.class);
                feeAdjust.setOrderId(req.getOrderId());
                feeAdjust.setTouristId(touristId);
                LocalDateTime now = LocalDateTime.now();
                feeAdjust.setGmtCreate(now);
                feeAdjust.setGmtModified(now);
                feeAdjust.setCreateId(req.getUserId());
                feeAdjust.setModifiedId(req.getUserId());
                feeAdjust.setIsDeleted(IsDeletedCode.NO.getCode());

                saveObjectList.add(feeAdjust);
            }
            
            //增加某旅客的调整费用
            iSeriesOrderTouristInfoService.addTouristAdjustmentAmount(touristId, allFeeAdjustAmount, req.getUserId());
        }

        iSeriesOrderTouristVisaService.saveOrUpdateBatch(saveVisaList);
        saveBatch(saveObjectList);
        
        return Result.success();
    }
    
    
    
    
    
    /**
     * 计算总其它费用
     * @param reqList
     * @return
     */
    private BigDecimal calcAllFeeAdjustAmount(List<SeriesOrderTouristFeeAdjustAddBatchItemReq> reqList) {
    	//调整总费用
    	BigDecimal allFeeAdjustAmount = BigDecimal.ZERO;
    	if (Assist.isNotEmpty(reqList)) {
    		for (SeriesOrderTouristFeeAdjustAddBatchItemReq req : reqList) {
    			if (req.getPlusType() != null && req.getAmount() != null) {
    				//加
    				if (PlusTypeCode.PLUS.getCode().equals(req.getPlusType())) {
    					allFeeAdjustAmount = allFeeAdjustAmount.add(req.getAmount());
    				} else if (PlusTypeCode.SUBTRACT.getCode().equals(req.getPlusType())) {  //减
    					allFeeAdjustAmount = allFeeAdjustAmount.subtract(req.getAmount());
    				}
    			}
			}
    	}
    	return allFeeAdjustAmount;
	}
}
